<?php

namespace app\api\service;

use think\facade\Db;
use WeChat\Pay;

class PaymentService
{


    /**
     * 生成订单号
     * @User zlchen
     * @param int $length
     * @param string $tab
     * @return string
     */
    public static function generateOrderNum($length = 6)
    {
        //20200606182556
        $dt = date('YmdHis');

        //5edb6bd-06f1a6  5edb6bd-292268   后6位不同
        $uniqid =  uniqid();

        //字符串截取 47b803
        $str_7_13 =  substr($uniqid, 7, 13);

        //str_split ( string $string [, int $split_length = 1 ] ) : array  str_split — 将字符串转换为数组
        $str_to_array = str_split($str_7_13, 1);

        //(PHP 4, PHP 5, PHP 7)  ord — 转换字符串第一个字节为 0-255 之间的值
        $arr = array_map('ord', $str_to_array); //[52,55,98,56,48,51]

        //implode — 将一个一维数组的值转化为字符串
        $arr_to_string =  implode(NULL, $arr);  //531015452102102

        //implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1)))
        //20200606182903102545
        $str = $dt . substr($arr_to_string, 0, $length);

        return $str;

    }

    /**
     * 获取支付配置信息
     * */
    public static function findPaymentConfig($store_id,$type)
    {
        $paymentConfig = Db::name('payment_config')->where(['store_id'=>$store_id,'type' => $type])->value('config');

        if (empty($paymentConfig)){
            return  [];
        }

        return  json_decode($paymentConfig,true);
    }


    public static function createOrder($data)
    {
        if ($data['trade_method']==1){
            $wechat = new Pay($data['config']);
            $options = [
                'body'             => '商品结算',
                'out_trade_no'     => $data['out_trade_no'],
                'total_fee'        => $data['real_amount']*100,
                'trade_type'       => 'APP',
                'notify_url'       => $data['notify_url'],
                'spbill_create_ip' => $_SERVER['REMOTE_ADDR']
            ];
            try {
                // 生成预支付码
                $result = $wechat->createOrder($options);
               
                $prepay_info = $wechat->createParamsForApp($result['prepay_id']);
                return $prepay_info;

            } catch (\Exception $e) {
                return [];
            }

        }

        if ($data['trade_method']==2){
            try {
                // 实例支付对象
                $pay = \We::AliPayApp($data['config']);
                $prepay_info = $pay->apply([
                    'out_trade_no' => $data['out_trade_no'], // 商户订单号
                    'total_amount' => $data['real_amount'],    // 支付金额
                    'subject'      => '商品结算', // 支付订单描述
                    'notify_url' => $data['notify_url']
                ]);
                return $prepay_info;
            } catch (\Exception $e) {
                return null;
            }
        }

        return  null;
    }

}